'use strict'
process.chdir(__dirname)
const titbit = require('titbit')
const fs = require('fs')
try{
    fs.accessSync('./images')
}catch(err){
    fs.mkdirSync('./images')
}

let cert_path='/usr/local/share'
const app = new titbit({
    //开始调试模式，会出现错误信息
    debug:true,
    cert:`${cert_path}/apiwec.wzryrjxy.xyz.pem`,
    key:`${cert_path}/apiwec.wzryrjxy.xyz.key`
})
//c就是content
app.get('/',async c=>{
    c.send('ok')
})
app.get('/upload',async c=>{
    //c.helper是助手函数模块，其中有对stream.pipe的封装
    //c.reply是响应对象，http/1.1中指向response.http/2中指向stream
    await c.helper.pipe('./upload.html',c.reply)
})
app.post('/upload',async c =>{
    let f = c.getFile('file')
    if(!f) {
        return c.status(400).send('file not found')
    }
    //生成唯一文件名
    let fname = c.helper.makeName(f.filename)
    try{
        await c.moveFile(f,`./images/${fname}`)
        c.send(fname)
    }catch(err){
        c.status(500).send('failed')
    }
})
app.get('/image/:name',async c =>{
    let imgname = c.param.name
    try{
        await c.helper.pipe(`./images/${imgname}`,c.reply)
    }catch(err){
        c.status(404).send('img not found')
    }
})
//js中如果是括号开头，前面要加一个分号
//js无需加分号，谁用谁知道，有事也得加分号，括号开头很需要
// ;(async()=>{

// })()
//监听1234端口运行服务
app.run(2006)